Page({
  data: {
    notifications: []
  },

  onLoad() {
    // this.getNotifications();
  },

  onShow() {
    this.getNotifications();
  },
  goToActivity(e) {
    const activityId = e.currentTarget.dataset.activityId;
    const commentId = e.currentTarget.dataset.commentId;
    if (activityId) {
      wx.navigateTo({
        url: `/pages/home/activity/activity?id=${activityId}${commentId ? `&commentId=${commentId}` : ''}`,
        success: () => {
          // 页面跳转成功后，等待页面加载完成再滚动到评论位置
          setTimeout(() => {
            const pages = getCurrentPages();
            const activityPage = pages[pages.length - 1];
            if (commentId && activityPage && activityPage.scrollToComment) {
              activityPage.scrollToComment(commentId);
            }
          }, 500);
        }
      });
    }
  },
  // 获取互动通知列表
  getNotifications() {
    const app = getApp();
    wx.request({
      url: app.globalData.onlineService + '/api/message/message',
      method: 'GET',
      data: {
        type: 'interaction',  // 指定获取互动类型的消息
        page: 1,
        page_size: 20
      },
      header: {
        'Authorization': `Bearer ${app.globalData.userInfo.token}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 更新消息列表
          this.setData({
            notifications: res.data.data
          });
          // 将获取到的未读消息标记为已读
          const unreadMessageIds = res.data.data
            .filter(msg => msg.status === 0)
            .map(msg => msg.id);
          
          if (unreadMessageIds.length > 0) {
            wx.request({
              url: app.globalData.onlineService + '/api/message/message',
              method: 'POST',
              data: {
                message_ids: unreadMessageIds
              },
              header: {
                'Authorization': `Bearer ${app.globalData.userInfo.token}`
              },
              success: (res) => {
                if (res.data.code === 200) {
                  console.log('消息状态更新成功');
                }
              },
              fail: (err) => {
                console.error('更新消息状态失败', err);
              }
            });
          }
        }
      },
      fail: (err) => {
        console.error('获取互动通知失败', err);
        wx.showToast({
          title: '获取通知失败',
          icon: 'none'
        });
      }
    });
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
});